package com.swufestu.hello;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class SecondActivity extends AppCompatActivity implements Runnable {

    private static final String TAG = "wwwwww";
    private final static long ONE_DAY_MSECOND = 24 * 60 * 60 * 1000;
    TextView out,input;
    private float dollarRate = 0.15438771f;
    private float euroRate = 0.13191742f;
    private float thbRate = 5.2532216f;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rate);

        input = findViewById(R.id.input);
        out = findViewById(R.id.out);//必须放在函数里

        //读取保存的数据
        SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        dollarRate = sp.getFloat("dollar_rate",dollarRate);
        euroRate = sp.getFloat("euro_rate",euroRate);
        thbRate = sp.getFloat("thb_rate",thbRate);
        Log.i(TAG,"onCreate: get from sp dollar=" + dollarRate);
        Log.i(TAG,"onCreate: get from sp euro=" + euroRate);
        Log.i(TAG,"onCreate: get from sp thb=" + thbRate);

        //获取当前线程对象
        handler = new Handler(Looper.myLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                Log.i(TAG,"handleMessage: 已收到消息");
                if(msg.what==6){
//                    String str = (String)msg.obj;
//                    Log.i(TAG,"handleMessage: str="+str);
//                    //收到msg后，在控件中显示
//                    out.setText(str);//?空指针问题
                    Bundle bdl = (Bundle)msg.obj;
                    dollarRate = bdl.getFloat("r1");
                    euroRate = bdl.getFloat("r2");
                    thbRate = bdl.getFloat("r3");

                    Log.i(TAG,"handleMessage: dollarRate:" + dollarRate);
                    Log.i(TAG,"handleMessage: euroRate:" + euroRate);
                    Log.i(TAG,"handleMessage: thbRate:" + thbRate);

                    Toast.makeText(SecondActivity.this,"汇率已更新",Toast.LENGTH_SHORT).show();
                }
                super.handleMessage(msg);
            }
        };

        //启动子线程
        MyThread td = new MyThread();
        td.setHanlder(handler);


        Thread t = new Thread(this);
        t.start();//this.run()自动运行

    }

    public void myclick(View btn) {
        Log.i(TAG, "OnClick:AAAAAAA");
        if (input.length() > 0) {
            float number = Float.parseFloat(input.getText().toString());
            float r = 0;
            if (btn.getId() == R.id.btn1) {
                r = dollarRate * number;
            } else if (btn.getId() == R.id.btn2) {
                r = euroRate * number;
            } else if (btn.getId() == R.id.btn3) {
                r = thbRate * number;
            }
            out = findViewById(R.id.res);
            out.setText(String.valueOf(r));
        } else {
            //重置输出
            out.setText(R.string.txt);
            Toast.makeText(this, "input again", Toast.LENGTH_SHORT).show();
        }
    }

    public void openConfig(View v) {
        Log.i(TAG, "openConfig");
        //打开窗口
        Intent config = new Intent(this, ConfigActivity.class);
        config.putExtra("dollar_rate_key", dollarRate);
        config.putExtra("euro_rate_key", euroRate);
        config.putExtra("thb_rate_key", thbRate);

        Log.i(TAG, "openConfig: dollarRate=" + dollarRate);
        Log.i(TAG, "openConfig: euroRate=" + euroRate);
        Log.i(TAG, "openConfig: thbRate=" + thbRate);

        startActivityForResult(config, 1);
    }

    public void config(){
        Intent config = new Intent(this,ConfigActivity.class);
        config.putExtra("dollar_rate_key",dollarRate);
        config.putExtra("euro_rate_key",euroRate);
        config.putExtra("thb_rate_key",thbRate);

        Log.i(TAG,"openConfig: dollarRate=" + dollarRate);
        Log.i(TAG,"openConfig: euroRate=" + euroRate);
        Log.i(TAG,"openConfig: thbRate=" + thbRate);

        startActivityForResult(config, 1);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode==1 && resultCode ==3){
            dollarRate = data.getFloatExtra("dollar_key",0.1f);
            euroRate = data.getFloatExtra("euro_key",0.1f);
            thbRate = data.getFloatExtra("thb_key",0.1f);

            Log.i(TAG,"onActivityResult: dollarRate= "+dollarRate);
            Log.i(TAG,"onActivityResult: euroRate= "+euroRate);
            Log.i(TAG,"onActivityResult: thbRate= "+thbRate);

            //保存数据到sp
            SharedPreferences sp = getSharedPreferences("myrate",Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putFloat("dollar_rate",dollarRate);
            editor.putFloat("euro_rate",euroRate);
            editor.putFloat("thb_rate",thbRate);
            editor.apply();
            Log.i(TAG,"onActivityResult: save to sp ok");
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.menu_setting){
            Log.i(TAG,"onOptionsItemSelected: setting....");
        }
        return super.onOptionsItemSelected(item);
    }

    //开启线程
    @Override
    public void run() {
        try{
            Thread.sleep(3000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        Log.i(TAG,"run: ......");

        //用于保存获取的数据
        Bundle bundle = new Bundle();

        Intent i = new Intent();
        //创建闹钟对象
        AlarmManager alarmManager = (AlarmManager)getSystemService(Service.ALARM_SERVICE);
        PendingIntent pi = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),ONE_DAY_MSECOND,pi);

        try{
            Document doc = Jsoup.connect("http://www.usd-cny.com/bankofchina.htm").get();
            Log.i(TAG,"run: title=" + doc.title());

//            Elements h4s = doc.getElementsByTag("h4");
//            for(Element h4 : h4s){
//                Log.i(TAG,"run: h4=" + h4.text());
//            }
            Elements tables = doc.getElementsByTag("table");
            Element table1 = tables.first();

//            Log.i(TAG,"run: table=" + table1);
            //读取某一label的属性
//            Elements hrefs = table1.getElementsByTag("a");
//            for(Element a : hrefs){
//                Log.i(TAG,"run: a=" + a.text());
//            }
            //获取tr元素
            Elements trs = table1.getElementsByTag("tr");
            trs.remove(0);
            for(Element tr : trs){
//                Log.i(TAG, "run: tr=" + tr);
                Elements tds = tr.getElementsByTag("td");
                String cname = tds.get(0).text();
                String cval = tds.get(5).text();
                Log.i(TAG,"run: cname=" + cname + " --> " + cval);

                if("美元".equals(cname)){
                    bundle.putFloat("r1", 100f/Float.parseFloat(cval));
                }else if("欧元".equals(cname)){
                    bundle.putFloat("r2", 100f/Float.parseFloat(cval));
                }else if("泰铢".equals(cname)){
                    bundle.putFloat("r3", 100f/Float.parseFloat(cval));
                }
            }
        }catch(MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

        //Bundle中保存获取的数据

        //获取MSG对象，发送消息给主线程
//        msg.what = 6;
//        msg.obj = "hello from run";
//        msg.obj = bundle;
        Message msg = handler.obtainMessage(6,bundle);
        handler.sendMessage(msg);
        Log.i(TAG,"run: 消息已发送");
    }

    private String inputStream2String(InputStream inputStream) throws IOException{
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream, "gb2312");
        while(true){
            int rsz = in.read(buffer,0,buffer.length);
            if(rsz < 0)
                break;
            out.append(buffer,0,rsz);
        }
        return out.toString();
    }

}